import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:wanAndroid/bean/project_model.dart';
import 'package:wanAndroid/common/http/http_service.dart';
import 'package:wanAndroid/common/http/http_uts.dart';
import 'package:wanAndroid/page/page_projectlist.dart';

class PageGuangChange extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageGuangChange();
}

class _PageGuangChange extends State<PageGuangChange>
    with TickerProviderStateMixin {
  var _projectList = <ProjectData>[];

  ///控制器
  TabController _tabController;

  ///当前tab index
  int _selectIndex = 0;

  @override
  void initState() {
    getProject();

    super.initState();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  ///初始化tabs
  void _initTabs() {
    _tabController = TabController(length: _projectList.length, vsync: this);
    _tabController.addListener(() {
      bool isChange = _tabController.index != _tabController.animation.value;
      if (isChange) return;
      _selectIndex = _tabController.index;
      _tabController.animateTo(
        _selectIndex,
        duration: Duration(
          milliseconds: 500,
        ),
      );
      print("========= $_selectIndex");
    });
  }

  @override
  Widget build(BuildContext context) => DefaultTabController(
        length: _projectList.isEmpty ? 0 : _projectList.length,
        child: Scaffold(
          backgroundColor: Color(0xfff1f1f1),
          appBar: AppBar(
            title: Row(
              children: [
                Expanded(
                  child: TabBar(
                    onTap: null,
                    indicatorColor: Colors.white,
                    labelColor: Colors.white,
                    unselectedLabelColor: Color(0xfff1f1f1),
                    labelStyle: TextStyle(
                      fontSize: 16,
                    ),
                    controller: _tabController,
                    isScrollable: true,
                    tabs: _projectList.map((e) => _getTabItem(e)).toList(),
                  ),
                )
              ],
            ),
          ),
          body: TabBarView(
            controller: _tabController,
            children: _projectList
                .map((e) => PageProjectList.start("${e.id}"))
                .toList(),
          ),
        ),
      );

  Widget _getTabItem(ProjectData data) {
    return Tab(
      text: "${data.name}",
    );
  }

  ///获取项目
  Future<void> getProject() async {
    HttpService.project(
      HttpCallback((resp) {
        ProjectModel projectModel = ProjectModel.fromJson(resp.data);
        if (HttpUts.isSuccess(projectModel.errorCode)) {
          setState(() {
            _projectList = projectModel.data;
          });

          ///初始化Tabs
          _initTabs();
        }
      }, (e) {}),
    );
  }
}
